package com.yuandengta.nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @Author:Hardy
 * @QQ:2937270766
 * @官网：http://www.yuandengta.com
 */
public class NIOServer {
    public static void main(String[] args) throws Exception{
        //创建ServerSocketChannel --> ServerSocket
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        //得到一个Selector对象
        Selector selector = Selector.open();

        //绑定端口6666,在服务器端监听
        serverSocketChannel.socket().bind(new InetSocketAddress(6666));
        //设置为非阻塞
        serverSocketChannel.configureBlocking(false);
        //把serverSocketChannel注册到selector,关心事件
        //为OP_ACCEPT
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        //循环等待客户端连接
        while(true){
            // 这里我们等到一秒，如果没有时间发生，返回
            if(selector.select(1000) == 0){
                System.out.println("服务器等待1秒，无连接");
            }
            //如果返回的不是>0
            //1、如果返回的大于0，表示已经获得到关注的事件
            //2、selector.selectedKeys（）返回关注的集合
            // 通过selectionKeys反向获取通道
            Set<SelectionKey> selectionKeys = selector.selectedKeys();

            Iterator<SelectionKey> ketyIterator = selectionKeys.iterator();
            while(ketyIterator.hasNext()){
                SelectionKey key = ketyIterator.next();
                //根据key对应的通道发生的事件做相应处理
                //如果是OP_ACCEPT，有新的客户端连接
                if(key.isAcceptable()){
                    //该客户端生成一个SocketChannel
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    System.out.println("客户端连接成功，生成一个socketChannel"+socketChannel.hashCode());
                    socketChannel.configureBlocking(false);
                    //将当前socketChannel注册到Selector上,关注事件为OP_READ，
                    //同时给socketChannel关联一个Buffer
                    socketChannel.register(selector,SelectionKey.OP_READ, ByteBuffer.allocate(1024));

                }
                if(key.isReadable()){//发生OP_READ
                    //通过key，反向获取到对应的channel
                    SocketChannel channel = (SocketChannel)key.channel();
                    //获取到channel关联的buffer
                    ByteBuffer buffer = (ByteBuffer)key.attachment();
                    channel.read(buffer);
                    System.out.println("from 客户端:"+new String(buffer.array()));

                }
                //手动从集合中移除当前selectionKey，避免重复操作
                ketyIterator.remove();
            }
        }
    }
}
